from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from contextlib import asynccontextmanager
import uvicorn
import time
import asyncio
from . import home
from . import login
from . import config
from . import plugin
from . import timer
from . import debug
from . import userdb
from . import vfs

t_start = time.time()

debug_cfg: dict = {}

if (config.read("demo")["demo"]):  # 演示模式
    # if (not config.read("debug")["debug"]):  # 非 debug 模式下启动演示模式
    #     print("==> Enable demo mode")
    #     # 启动新管理进程
    #     print(
    #         f"    Start demo server on port {str(config.read('demo')['port'])}...")
    #     subprocess.Popen([sys.executable, sys.argv[0],
    #                       "--set-config:security.demo=True",
    #                       "--set-config:debug.debug=False",
    #                       "--set-config:demo.demo=False",
    #                       "--set-config:server.port=" +
    #                       str(config.read("demo")["port"]),
    #                       "--set-config:account.username=demo",
    #                       "--set-config:account.password=demo"
    #                       ])
    #     print("    Waiting...")
    #     time.sleep(10)
    # else:
    config.configs["security"]["demo"] = True


if (config.read("debug")["debug"]):
    print("==> Enable debug mode")
    debug.load_dbg_mode()  # 调试模式
    debug_cfg = {
        "debug": True
    }
    uvi_cfg = {
        "reload": True,
        "reload_dirs": [],
        "reload_includes": ["*.py", "*.html", "*.toml", "*.json"]
    }
else:  # 禁用文档
    debug_cfg = {
        "docs_url": None,
        "redoc_url": None,
        "debug": False
    }
    uvi_cfg = {
        "reload": False
    }


@asynccontextmanager
async def lifespan(app: FastAPI):
    global t_start
    userdb.init()  # 加载数据库
    # 初始化计时器
    await timer.main()
    print(f"Load time: [{time.time()-t_start}]")
    yield

app = FastAPI(**debug_cfg, lifespan=lifespan)


if (config.read("debug")["debug"]):
    debug.add_timer(app)  # 服务端请求计时

# 挂载静态内容
app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="src")

# 加载插件
plugin.load_plugin(app)

# 加载页面
login.main(app, templates)
home.main(app, templates)

if (config.read("debug")["debug"]):
    uvi_cfg["reload_dirs"] = debug.DBG_LST+["src", "server", "config"]


def main():
    uvicorn.run("server.main:app", host=config.read("server")[
                "host"], port=config.read("server")["port"], **uvi_cfg)
